package com.hongxun.design.activitys.serviceandclient;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.FilesViewActivity;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.utils.socketutil.LongWriterAndReader;
import com.hongxun.design.bean.service.MessageData;
import com.hongxun.design.utils.socketutil.ReciveAndSend;


/**
 * Created by zerdoor_pc on 2016/4/22.
 * 热点服务器
 */
public class ServiceLong extends BaseActivity {
    private EditText edtext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_socket);
        TextView text = (TextView) findViewById(R.id.text);

        text.setText("server");
        MyLog.L(MyApp.AppName + ": server");
        Button btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), FilesViewActivity.class);
                startActivityForResult(intent, 0);
            }
        });
        edtext = (EditText) findViewById(R.id.edtext);
        Button btnSendtext = (Button) findViewById(R.id.btnSendtext);
        btnSendtext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageData = ReciveAndSend.getMessageData(1, edtext.getText().toString(), "");
                sendToAll();
            }
        });


        start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //选择了文件发送
        if (resultCode == RESULT_OK) {
            String fileName = data.getStringExtra("FileName");
            String path = data.getStringExtra("FilePath");
            messageData = ReciveAndSend.getMessageData(4, path, fileName);
//            messageData = ReciveAndSend.getMessageData(1, "消息", "");
            sendToAll();
        }
    }

    private void sendToAll() {
        if (threadList.size() > 0) {
            for (SocketThread thread : threadList) {
                try {
                    thread.writer();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    private final static String SOAP_BEGIN = "<SOAP-ENV:Envelope";
    private final static String SOAP_END = "</SOAP-ENV:Envelope>";
    private int prot = 8088;
    private MessageData messageData;
    private List<SocketThread> threadList = new ArrayList<>();
    private boolean isOnline = true;

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ServerSocket serverSocket = null;
                try {
                    serverSocket = new ServerSocket(prot);
                   //serverSocket.bind(new InetSocketAddress("192.168.2.2",prot));
                    while (isOnline) {
                        Socket socket = serverSocket.accept();
                        String ip=getIP(socket);
                        if (ips.contains(ip)){
                            for (int i=0;i<ips.size();i++){
                                if (ips.get(i).equals(ip)){
                                    try {
                                        threadList.get(i).close();
                                        threadList.remove(i);
                                        ips.remove(i);
                                    }catch (Exception e){}

                                }
                            }
                        }
                        SocketThread socketThread = new SocketThread(socket);
                        socketThread.start();
                        threadList.add(socketThread);
                        ips.add(ip);
                        socketThread.writerHeart();
                        MyLog.L(MyApp.AppName + "threadList:" + threadList);
                        MyLog.L(MyApp.AppName + "threadList:" + threadList.size());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
    private List<String> ips=new ArrayList<>();
    private static String getIP(Socket client) {
        String s = String.valueOf(client.getRemoteSocketAddress());
        String[] tar = s.replaceAll("/", "").split(":");
//        if (tar != null && tar.length > 0) {
//            if (!ips.contains(tar[0])) {
//                ips.add(tar[0]);
//
//            }
//         }
         return tar[0];
    }
    class SocketThread extends Thread {
        private Socket socket;
        private String temp;
        private boolean isopen = true;
        private boolean canSend = true;

        public Socket getSocket() {
            return socket;
        }

        public void setSocket(Socket socket) {
            this.socket = socket;
        }

        public SocketThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                while (isopen) {
                    String i = LongWriterAndReader.reader(in, true, canSend);//读取数据
                    Thread.sleep(3000);
//                    LongWriterAndReader.flag=true;
//                    if (i == 0) {
                    LongWriterAndReader.writer(out, 0,canSend);
//                    }else if (i==11){
//                        LongWriterAndReader.writer(out, 1);
//                    }
                }
//                Reader reader = new InputStreamReader(socket.getInputStream());
//                Writer writer = new PrintWriter(new OutputStreamWriter(socket
//                        .getOutputStream(), "utf-8"));
//                int readIndex = -1;
//                CharBuffer charBuffer = CharBuffer.allocate(8192);
//                int readIndex = -1;
//                while ((readIndex = reader.read(charBuffer)) != -1) {
//                    charBuffer.flip();
//                    temp += charBuffer.toString();
//                    if (temp.indexOf(SOAP_BEGIN) != -1
//                            && temp.indexOf(SOAP_END) != -1) {
//                        // 传送一个soap报文
//                        MyLog.L(MyApp.AppName +  "server:" + temp);
//                        temp="";
//                        writer.write("receive the soap message");
//                        writer.flush();
//                    } else if (temp.indexOf(SOAP_BEGIN) != -1) {
//                        // 包含开始，但不包含
//                        temp = temp.substring(temp.indexOf(SOAP_BEGIN));
//                        MyLog.L(MyApp.AppName +  "server2:" + temp);
//                    }
//                    if (temp.length() > 1024 * 16) {
//                        MyLog.L(MyApp.AppName +  "server3:break;" + temp);
//                        break;
//                    }
//                }
            } catch (Exception e) {
                MyLog.L(MyApp.AppName + "server1:" + e.toString());
            } finally {
                if (socket != null) {
                    if (!socket.isClosed()) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }

        public void writer() throws IOException {
            if (messageData == null) return;
            LongWriterAndReader.writer(socket.getOutputStream(), messageData,canSend);
            messageData = null;
        }

        public void writerHeart()  {
            try {
                LongWriterAndReader.writer(socket.getOutputStream(), 0,canSend);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void close() {
            isopen = false;
        }

    }


    @Override
    protected void onDestroy() {
        for (SocketThread thread : threadList) {
            thread.close();
        }
        isOnline = false;
        super.onDestroy();
    }


    public String getNetworkIpAddress(String name) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> enumeration = networkInterface.getInetAddresses();
                while (enumeration.hasMoreElements()) {
                    InetAddress inetAddress = enumeration.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address
                            && TextUtils.equals(name, networkInterface.getDisplayName())){
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getApName(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Method method = connectivityManager.getClass().getMethod("getTetheredIfaces");
            String[] names = (String[]) method.invoke(connectivityManager);
            return names[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
